package com.trace.demo.controller;

import com.trace.demo.entity.FarmingActivity;
import com.trace.demo.entity.User;
import com.trace.demo.repository.FarmingActivityRepository;
import com.trace.demo.repository.UserRepository;
import com.trace.demo.response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserRepository userRepository;
    private final FarmingActivityRepository activityRepository;
    private final BCryptPasswordEncoder passwordEncoder;

    @Autowired
    public UserController(UserRepository userRepository,
                         FarmingActivityRepository activityRepository) {
        this.userRepository = userRepository;
        this.activityRepository = activityRepository;
        this.passwordEncoder = new BCryptPasswordEncoder();
    }

    /**
     * 创建错误响应Map
     * @param errorMessage 错误信息
     * @return 错误响应Map
     */
    private Map<String, Object> createErrorMap(String errorMessage) {
        Map<String, Object> errorMap = new HashMap<>();
        errorMap.put("error", errorMessage);
        return errorMap;
    }

    /**
     * 创建成功响应Map
     * @param message 成功信息
     * @param data 响应数据
     * @return 成功响应Map
     */
    private Map<String, Object> createSuccessMap(String message, Object data) {
        Map<String, Object> successMap = new HashMap<>();
        successMap.put("success", true);
        successMap.put("message", message);
        successMap.put("data", data);
        return successMap;
    }

    /**
     * 用户登录
     * @param loginData 登录数据
     * @return 登录成功的用户信息
     */
    @PostMapping("/login-legacy")
    public ResponseEntity<?> loginUser(@RequestBody Map<String, String> loginData) {
        try {
            String username = loginData.get("username");
            String password = loginData.get("password");

            if (username == null || password == null) {
                return ResponseEntity.badRequest().body(createErrorMap("用户名和密码不能为空"));
            }

            return userRepository.findByUsernameAndPassword(username, password)
                    .map(user -> {
                        // 记录登录活动
                        FarmingActivity activity = new FarmingActivity();
                        activity.setUser(user);
                        activity.setType("system");
                        activity.setContent("用户登录系统");
                        activityRepository.save(activity);

                        // 返回用户信息
                        Map<String, Object> result = new HashMap<>();
                        result.put("user", user);
                        return ResponseEntity.ok(result);
                    })
                    .orElse(ResponseEntity.badRequest().body(createErrorMap("用户名或密码错误")));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorMap("登录失败: " + e.getMessage()));
        }
    }

    /**
     * 获取当前用户信息
     * @return 用户信息
     */
    @GetMapping("/current/{username}")
    public ResponseEntity<User> getCurrentUser(@PathVariable String username) {
        try {
            return userRepository.findByUsername(username)
                    .map(user -> {
                        // 出于安全考虑，不返回密码
                        user.setPassword(null);
                        return ResponseEntity.ok(user);
                    })
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
        } catch (Exception e) {
            throw new RuntimeException("获取用户信息失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前用户信息（通过token）
     * @return 用户信息
     */
    @GetMapping("/profile")
    public ResponseEntity<ApiResponse<User>> getCurrentUserByToken(@RequestHeader(value = "Authorization", required = false) String token) {
        try {
            // 从token中获取用户ID
            Long userId = extractUserIdFromToken(token);
            if (userId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(new ApiResponse<>(false, "未授权访问", null));
            }
            
            Optional<User> userOptional = userRepository.findById(userId);
            if (!userOptional.isPresent()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "用户不存在", null));
            }
            
            User user = userOptional.get();
            user.setPassword(null); // 安全处理：移除密码
            
            return ResponseEntity.ok(new ApiResponse<>(true, "获取用户信息成功", user));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "获取用户信息失败: " + e.getMessage(), null));
        }
    }

    /**
     * 获取用户通知设置
     */
    @GetMapping("/notification-settings")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getNotificationSettings(@RequestHeader(value = "Authorization", required = false) String token) {
        try {
            // 从token中获取用户ID
            Long userId = extractUserIdFromToken(token);
            if (userId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(new ApiResponse<>(false, "未授权访问", null));
            }
            
            // 在实际应用中，这些设置应该从数据库读取
            // 这里提供默认设置
            Map<String, Object> notificationSettings = new HashMap<>();
            notificationSettings.put("emailNotifications", true);
            notificationSettings.put("smsNotifications", false);
            notificationSettings.put("pushNotifications", true);
            
            Map<String, Boolean> eventSettings = new HashMap<>();
            eventSettings.put("orderUpdates", true);
            eventSettings.put("logistics", true);
            eventSettings.put("productUpdates", false);
            eventSettings.put("promotions", false);
            eventSettings.put("systemAnnouncements", true);
            
            notificationSettings.put("events", eventSettings);
            
            return ResponseEntity.ok(new ApiResponse<>(true, "获取通知设置成功", notificationSettings));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "获取通知设置失败: " + e.getMessage(), null));
        }
    }
    
    /**
     * 更新用户通知设置
     */
    @PutMapping("/notification-settings")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateNotificationSettings(
            @RequestHeader(value = "Authorization", required = false) String token,
            @RequestBody Map<String, Object> notificationSettings) {
        try {
            // 从token中获取用户ID
            Long userId = extractUserIdFromToken(token);
            if (userId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(new ApiResponse<>(false, "未授权访问", null));
            }
            
            // 在实际应用中，这里会将设置保存到数据库
            // 此处仅返回更新成功的响应
            
            return ResponseEntity.ok(new ApiResponse<>(true, "更新通知设置成功", notificationSettings));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "更新通知设置失败: " + e.getMessage(), null));
        }
    }
    
    /**
     * 从Authorization头中提取用户ID
     */
    private Long extractUserIdFromToken(String token) {
        if (token == null || token.isEmpty()) {
            return null;
        }
        
        // 示例中使用简单的token格式: "Bearer mock-jwt-token-{userId}"
        if (token.startsWith("Bearer mock-jwt-token-")) {
            try {
                String userIdStr = token.substring("Bearer mock-jwt-token-".length());
                return Long.parseLong(userIdStr);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        
        return null;
    }

    /**
     * 获取所有用户
     * 
     * @param page 页码
     * @param size 每页数量
     * @param sort 排序字段
     * @param direction 排序方向
     * @param status 状态过滤
     * @param role 角色过滤
     * @param keyword 关键词搜索
     * @return 用户列表
     */
    @GetMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> getAllUsers(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "id") String sort,
            @RequestParam(defaultValue = "asc") String direction,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) User.UserRole role,
            @RequestParam(required = false) String keyword) {
        
        try {
            // 创建排序对象
            Sort.Direction sortDirection = "desc".equalsIgnoreCase(direction) ? Sort.Direction.DESC : Sort.Direction.ASC;
            Sort sortObj = Sort.by(sortDirection, sort);
            
            // 创建分页对象
            PageRequest pageRequest = PageRequest.of(page, size, sortObj);
            
            // 查询用户列表
            Page<User> userPage;
            
            if (keyword != null && !keyword.isEmpty()) {
                // 关键词搜索
                userPage = userRepository.findByUsernameContaining(keyword, pageRequest);
            } else if (status != null && role != null) {
                // 按状态和角色过滤
                userPage = userRepository.findByStatusAndRole(status, role, pageRequest);
            } else if (status != null) {
                // 只按状态过滤
                userPage = userRepository.findByStatus(status, pageRequest);
            } else if (role != null) {
                // 只按角色过滤
                userPage = userRepository.findByRole(role, pageRequest);
            } else {
                // 无过滤条件
                userPage = userRepository.findAll(pageRequest);
            }
            
            // 安全处理：移除密码
            List<User> secureUsers = userPage.getContent().stream()
                    .peek(user -> user.setPassword(null))
                    .collect(Collectors.toList());
            
            // 构建响应数据
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("content", secureUsers);
            responseData.put("totalElements", userPage.getTotalElements());
            responseData.put("totalPages", userPage.getTotalPages());
            responseData.put("currentPage", userPage.getNumber());
            responseData.put("size", userPage.getSize());
            
            return ResponseEntity.ok(new ApiResponse<>(true, "获取用户列表成功", responseData));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "获取用户列表失败: " + e.getMessage(), null));
        }
    }

    /**
     * 获取用户信息
     * @param id 用户ID
     * @return 用户信息
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<User>> getUserById(@PathVariable Long id) {
        Optional<User> userOptional = userRepository.findById(id);
        
        if (!userOptional.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "用户不存在", null));
        }
        
        User user = userOptional.get();
        user.setPassword(null); // 安全处理：移除密码
        
        return ResponseEntity.ok(new ApiResponse<>(true, "获取用户信息成功", user));
    }

    /**
     * 根据角色获取用户列表
     * @param role 角色
     * @return 用户列表
     */
    @GetMapping("/role/{role}")
    public ResponseEntity<?> getUsersByRole(@PathVariable User.UserRole role) {
        try {
            List<User> users = userRepository.findByRole(role);
            // 出于安全考虑，不返回密码
            users.forEach(user -> user.setPassword(null));
            return ResponseEntity.ok(users);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorMap("获取用户列表失败: " + e.getMessage()));
        }
    }

    /**
     * 创建用户
     * 
     * @param user 用户信息
     * @return 创建结果
     */
    @PostMapping
    public ResponseEntity<ApiResponse<User>> createUser(@RequestBody User user) {
        try {
            // 验证必要字段
            if (user.getUsername() == null || user.getPassword() == null || user.getRole() == null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(false, "用户名、密码和角色不能为空", null));
            }
            
            // 检查用户名是否已存在
            if (userRepository.existsByUsername(user.getUsername())) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(false, "用户名已存在", null));
            }
            
            // 加密密码
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            
            // 设置默认值
            user.setCreatedAt(LocalDateTime.now());
            user.setUpdatedAt(LocalDateTime.now());
            if (user.getStatus() == null) {
                user.setStatus(1); // 默认启用
            }
            
            User savedUser = userRepository.save(user);
            
            // 记录活动
            FarmingActivity activity = new FarmingActivity();
            activity.setUser(savedUser);
            activity.setType("system");
            activity.setContent("创建了新用户: " + savedUser.getUsername());
            activityRepository.save(activity);
            
            // 安全处理：移除密码
            savedUser.setPassword(null);
            
            return ResponseEntity.status(HttpStatus.CREATED)
                    .body(new ApiResponse<>(true, "用户创建成功", savedUser));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "用户创建失败: " + e.getMessage(), null));
        }
    }

    /**
     * 更新用户信息
     * 
     * @param id 用户ID
     * @param user 更新的用户信息
     * @return 更新结果
     */
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<User>> updateUser(@PathVariable Long id, @RequestBody User user) {
        try {
            Optional<User> userOptional = userRepository.findById(id);
            
            if (!userOptional.isPresent()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "用户不存在", null));
            }
            
            User existingUser = userOptional.get();
            
            // 更新字段（保留ID和创建时间不变）
            if (user.getUsername() != null && !user.getUsername().equals(existingUser.getUsername())) {
                // 如果修改了用户名，需检查是否已存在
                if (userRepository.existsByUsername(user.getUsername())) {
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                            .body(new ApiResponse<>(false, "用户名已存在", null));
                }
                existingUser.setUsername(user.getUsername());
            }
            
            // 密码单独处理，防止覆盖已加密的密码
            if (user.getPassword() != null && !user.getPassword().isEmpty()) {
                existingUser.setPassword(passwordEncoder.encode(user.getPassword()));
            }
            
            // 更新其他字段
            if (user.getEmail() != null) existingUser.setEmail(user.getEmail());
            if (user.getPhone() != null) existingUser.setPhone(user.getPhone());
            if (user.getRole() != null) existingUser.setRole(user.getRole());
            if (user.getAvatar() != null) existingUser.setAvatar(user.getAvatar());
            if (user.getAddress() != null) existingUser.setAddress(user.getAddress());
            if (user.getStatus() != null) existingUser.setStatus(user.getStatus());
            
            existingUser.setUpdatedAt(LocalDateTime.now());
            User updatedUser = userRepository.save(existingUser);
            
            // 记录活动
            FarmingActivity activity = new FarmingActivity();
            activity.setUser(updatedUser);
            activity.setType("system");
            activity.setContent("更新了用户信息: " + updatedUser.getUsername());
            activityRepository.save(activity);
            
            // 安全处理：移除密码
            updatedUser.setPassword(null);
            
            return ResponseEntity.ok(new ApiResponse<>(true, "用户信息更新成功", updatedUser));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "用户信息更新失败: " + e.getMessage(), null));
        }
    }

    /**
     * 删除用户
     * 
     * @param id 用户ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteUser(@PathVariable Long id) {
        try {
            Optional<User> userOptional = userRepository.findById(id);
            
            if (!userOptional.isPresent()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "用户不存在", null));
            }
            
            User user = userOptional.get();
            
            // 执行软删除（设置状态为禁用）
            user.setStatus(0);
            user.setUpdatedAt(LocalDateTime.now());
            userRepository.save(user);
            
//             也可执行硬删除（从数据库移除）
             userRepository.delete(user);
            
            return ResponseEntity.ok(new ApiResponse<>(true, "用户删除成功", null));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "用户删除失败: " + e.getMessage(), null));
        }
    }

    /**
     * 批量删除用户
     * 
     * @param ids 用户ID列表
     * @return 删除结果
     */
    @DeleteMapping("/batch")
    public ResponseEntity<ApiResponse<Void>> batchDeleteUsers(@RequestBody List<Long> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(false, "用户ID列表不能为空", null));
            }
            
            List<User> users = userRepository.findAllById(ids);
            
            // 执行软删除
            for (User user : users) {
                user.setStatus(0);
                user.setUpdatedAt(LocalDateTime.now());
            }
            
            userRepository.saveAll(users);
            
            return ResponseEntity.ok(new ApiResponse<>(true, "批量删除用户成功", null));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "批量删除用户失败: " + e.getMessage(), null));
        }
    }

    /**
     * 更新用户状态
     * 
     * @param id 用户ID
     * @param status 状态值
     * @return 更新结果
     */
    @PutMapping("/{id}/status")
    public ResponseEntity<ApiResponse<User>> updateUserStatus(
            @PathVariable Long id, 
            @RequestBody Map<String, Integer> statusData) {
        
        try {
            Integer status = statusData.get("status");
            
            if (status == null || (status != 0 && status != 1)) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(false, "状态值无效，必须为0或1", null));
            }
            
            Optional<User> userOptional = userRepository.findById(id);
            
            if (!userOptional.isPresent()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "用户不存在", null));
            }
            
            User user = userOptional.get();
            user.setStatus(status);
            user.setUpdatedAt(LocalDateTime.now());
            
            User updatedUser = userRepository.save(user);
            updatedUser.setPassword(null); // 安全处理
            
            return ResponseEntity.ok(new ApiResponse<>(true, 
                    status == 1 ? "用户已启用" : "用户已禁用", 
                    updatedUser));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "更新用户状态失败: " + e.getMessage(), null));
        }
    }

    /**
     * 重置用户密码
     * 
     * @param id 用户ID
     * @param passwordData 包含新密码的数据
     * @return 重置结果
     */
    @PutMapping("/{id}/password")
    public ResponseEntity<ApiResponse<Void>> resetPassword(
            @PathVariable Long id,
            @RequestBody Map<String, String> passwordData) {
        
        try {
            String newPassword = passwordData.get("password");
            
            if (newPassword == null || newPassword.isEmpty()) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(false, "新密码不能为空", null));
            }
            
            Optional<User> userOptional = userRepository.findById(id);
            
            if (!userOptional.isPresent()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "用户不存在", null));
            }
            
            User user = userOptional.get();
            
            // 加密并设置新密码
            user.setPassword(passwordEncoder.encode(newPassword));
            user.setUpdatedAt(LocalDateTime.now());
            
            userRepository.save(user);
            
            return ResponseEntity.ok(new ApiResponse<>(true, "密码重置成功", null));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "密码重置失败: " + e.getMessage(), null));
        }
    }

    /**
     * 按角色统计用户数量
     * 
     * @return 统计结果
     */
    @GetMapping("/statistics/by-role")
    public ResponseEntity<ApiResponse<Map<String, Object>>> countUsersByRole() {
        try {
            List<Object[]> roleCounts = userRepository.countUsersByRole();
            
            Map<String, Object> statistics = new HashMap<>();
            for (Object[] count : roleCounts) {
                String role = count[0].toString();
                Long number = (Long) count[1];
                statistics.put(role, number);
            }
            
            // 计算总数
            long total = userRepository.count();
            statistics.put("TOTAL", total);
            
            return ResponseEntity.ok(new ApiResponse<>(true, "获取用户角色统计成功", statistics));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "获取用户角色统计失败: " + e.getMessage(), null));
        }
    }
}
